<?php

namespace app\controller;

use app\BaseController;
use app\common\Amap;
use app\common\UsersService;
use app\model\HkArea;
use app\model\Message;
use app\model\SecGoods;
use app\model\SecGoodsClass;
use app\model\SecGoodsComment;
use app\model\UsersRelated;
use app\model\UsersShield;
use app\Request;
use think\db\Query;
use think\response\Json;

class SecGoodsController extends BaseController
{
    protected array $middleware = [
        'Login' => ['except' => ['index', 'class', 'test','read','comment_list','map','map_detail']],
        'Location' => ['only' => ['index', '']],
    ];
	
	/**
	 * 屏蔽
	 * @param Request $request
	 * @return void
	 */
	function shield(Request $request)
	{
		$id = $request->post('id/d');
		UsersShield::create([
			'users_id'=>$request->users_id,
			'pro_id'=>$id,
			'type'=>'secgoods'
		]);
		writeJson();
	}
	
	
	/**
	 * 二手物品-列表
	 * @param int $class_id
	 * @param string $keyword
	 * @param int $default
	 * @param mixed $hk_area_id
	 * @return Json
	 */
    function index(Request $request,int $class_id, string $keyword,int $default, mixed $hk_area_id): Json
    {
	    $shield = UsersShield::where(['users_id'=>$request->users_id,'type'=>'secgoods'])->column('pro_id');
	    
	    $lat = self::$latitude;
        $lng = self::$longitude;
        $rows = SecGoods::field("*,(6371 * acos (cos ( radians($lat) ) * cos( radians( latitude ) ) * cos( radians(longitude) - radians( $lng ) ) + sin ( radians( $lat ) ) * sin( radians( latitude ) ))) AS distance")
            ->with(['users'])
            ->filter(function ($data) use($lat,$lng) {
                if (empty($lat) || empty($lng)) {
                    $data->distance_text = '';
                } else {
	                if (empty($data->latitude)||empty($data->longitude)){
		                $data->distance_text = '';
	                }else{
		                if ($data->distance == 0) {
			                $data->distance_text = '0m';
		                } elseif (0 < $data->distance && $data->distance < 1) {
						
			                $data->distance_text = bcmul(number_format($data->distance,6), '1000') . 'm';
		                } else {
			                $data->distance_text = bcmul((string)$data->distance, '1', 1) . 'km';
		                }
	                }
                }

            })
	        ->whereNotIn('id',$shield)
	        ->when(!empty($hk_area_id)&&$hk_area_id!=3, function (Query $query) use ($hk_area_id) {
		        $query->whereFindInSet('hk_area_ids',$hk_area_id);
	        })
            ->when(!empty($class_id), function (Query $query) use ($class_id) {
                if ($class_id == -1) {
                    $query->where('price', 0);
                } elseif ($class_id == -2) {
                  //留空
                } else {
                    $query->where('class_id', $class_id);
                }
            })
            ->when(!empty($keyword), function (Query $query) use ($keyword) {
                $query->whereLike('content', '%' . $keyword . '%');
            })
            ->when(!empty($default),function (Query $query)use($default,$lng,$lat){
                switch ($default){
                    case 1:
                        $query->order(['id'=>'desc']);
                        break;
                    case 2:
                        $query->order(['browse'=>'desc']);
                        break;
                    case 3:
                        $query->order(['createtime'=>'desc']);
                        break;
                    case 4:
                        $query->where('images','<>','');
                        break;
                    case 5:
	                    if (empty($lat)||empty($lng)){
		                    $query->order('createtime', 'desc');
	                    }else{
		                    $query->order('distance', 'asc');
	                    }
	                    break;
                }
            })
            ->paginate()
            ->items();
        writeJson($rows);
    }
	
	/**
	 * 地图
	 * @param float $latitude
	 * @param float $longitude
	 * @param int $distance
	 * @param int $class_id
	 * @param string $keyword
	 * @param int $default
	 * @param mixed $hk_area_id
	 * @return Json
	 */
	function map(float $latitude,float $longitude,int $distance,int $class_id, string $keyword,int $default, mixed $hk_area_id): Json
	{
		$lat = $latitude;
		$lng = $longitude;
		$res = SecGoods::
		field("*,(6371 * acos (cos ( radians($lat) ) * cos( radians( latitude ) ) * cos( radians(longitude) - radians( $lng ) ) + sin ( radians( $lat ) ) * sin( radians( latitude ) ))) AS distance")
			->filter(function ($data) use($lat,$lng) {
				if (empty($lat) || empty($lng)) {
					$data->distance_text = '';
				} else {
					if ($data->distance == 0) {
						$data->distance_text = '0m';
					} elseif (0 < $data->distance && $data->distance < 1) {
						$data->distance_text = bcmul(number_format($data->distance,6), '1000') . 'm';
					} else {
						$data->distance_text = bcmul((string)$data->distance, '1', 1) . 'km';
					}
				}
				
			})
			->when(!empty($class_id), function (Query $query) use ($class_id) {
				if ($class_id == -1) {
					$query->where('price', 0);
				} elseif ($class_id == -2) {
					$query->order(['like' => 'desc']);
				} else {
					$query->where('class_id', $class_id);
				}
			})
			->when(!empty($hk_area_id)&&$hk_area_id!=3, function (Query $query) use ($hk_area_id) {
				$query->whereFindInSet('hk_area_ids',$hk_area_id);
			})
			->when(!empty($keyword), function (Query $query) use ($keyword) {
				$query->whereLike('content', '%' . $keyword . '%');
			})
			->when(!empty($default),function (Query $query)use($default){
				switch ($default){
					case 1:
						$query->order(['id'=>'desc']);
						break;
					case 2:
						$query->order(['browse'=>'desc']);
						break;
					case 3:
						$query->order(['createtime'=>'desc']);
						break;
					case 4:
						$query->where('images','<>','');
						break;
					case 5:
						$query->order(['distance'=>'desc']);
						break;
				}
			})
			->having("distance<=$distance")
			->select();
		writeJson($res);
	}
	
	/**
	 * 二手物品-详情
	 * @param Request $request
	 * @param $id
	 * @return Json
	 */
    function read(Request $request, $id)
    {
        $row = SecGoods::with([
            'users' => function (Query $query) {
                $query->filter(function ($data) {
                    $receive = Message::where(['to_users_id' => $data->id])->whereTime('createtime', 'day')->column('from_users_id');//近24小时收到消息的数量
                    $send = Message::where(['from_users_id' => $data->id])->whereIn('to_users_id', $receive)->whereTime('createtime', 'day')->select();//近24小时回复消息的数量
                    $receive_count = count($receive);
                    $send_count = $send->count();
                    if ($receive_count == 0) {
                        $data->hours_24 = "24小时回复率100%";
                    } else {
                        $data->hours_24 = "24小时回复率" . round($send_count / $receive_count * 100, 2) . "%";
                    }
                    $second = 0;
                    foreach ($send as $k) {
                        $receive = Message::where(['to_users_id' => $data->id, 'from_users_id' => $k->to_users_id])->whereTime('createtime', 'day')->find();
                        $second += $k->getData('createtime') - $receive->getData('createtime');
                    }
                    if ($send_count == 0) {
                        $data->hours_avg = '平均0小时回复';
                    } else {
                        $data->hours_avg = '平均' . round($second / 3600 / $send_count, 1) . '小时回复';
                    }
                });
            },
            'class',
            'users_like' => function (Query $query) use ($request) {
                $query->where(['users_id' => $request->users_id, 'type' => 'secgoods']);
            },
            'users_collect' => function (Query $query) use ($request) {
                $query->where(['users_id' => $request->users_id, 'type' => 'secgoods']);
            },
        ])->findOrFail($id);
        event('SecGoodsIncBrowse', $id); //增加浏览数量
        UsersService::footmark($id, $request->users_id, 'secgoods');
        writeJson($row);
    }
	
	
	/**
	 * 二手物品-类目
	 * @return Json
	 */
    function class(): Json
    {
        $res = SecGoodsClass::paginate()->items();
        writeJson($res);
    }

    /**
     * 二手物品-发布
     * @param Request $request
     * @return Json
     */
    function save(Request $request): Json
    {
        $params = $request->param();
	    if (!empty($params['longitude'])&&!empty($params['latitude'])){
		    $ids = HkArea::where([['top','>=',$params['latitude']],['bottom','<=',$params['latitude']],['left','<=',$params['longitude']],['right','>=',$params['longitude']]])->column('id');
		    $ids = implode(',',$ids);
		    $params['hk_area_ids'] = $ids;
	    }
	    
	    $res = SecGoods::create($params);
        writeJson($res->append(['users']));
    }

    /**
     * 评论
     * @param Request $request
     * @return Json
     */
    function comment(Request $request): Json
    {
        $params = $request->param();//goods_id   to_users_id  pid  content

        $ip = $request->ip();
        $params['ip'] = $ip;
        $ip = Amap::ip($ip);
        $ip = json_decode($ip);
        if ($ip->status == 1) {
            $params['city'] = $ip->province;
        } else {
            $params['city'] = '未知';
        }

        $res = SecGoodsComment::create($params);
        foreach ($params['content'] as $v) {
            if ($v['type'] == 'at') {
                //@提醒  提醒接收人
                UsersRelated::create(['users_id' => $v['userId'], 'type' => 8, 'from_users_id' => $request->users_id, 'scene' => 'SecGoods', 'pro_id' => $res->id]);
            }
        }
        if (!empty($params['to_users_id'])) {
            //回复提醒  提醒接收人
            UsersRelated::create(['users_id' => $params['to_users_id'], 'type' => 1, 'from_users_id' => $request->users_id, 'scene' => 'SecGoods', 'pro_id' => $res->id]);
        } else {
            //评论提醒  提醒发布人
            $pro = SecGoods::find($params['goods_id']);
            UsersRelated::create(['users_id' => $pro->users_id, 'type' => 2, 'from_users_id' => $request->users_id, 'scene' => 'SecGoods', 'pro_id' => $res->id]);
        }
        event('SecGoodsIncComment', $params['goods_id']); //增加评论数量
        $row = SecGoodsComment::with(['users', 'to_users', 'users_like' => function (Query $query) use ($request) {
            $query->where(['users_id' => $request->users_id, 'type' => 'secgoods_comment']);
        }])->find($res->id);
        writeJson($row);
    }
	
	/**
	 * 评论列表
	 * @param int $goods_id
	 * @param mixed $comment_id
	 * @param Request $request
	 * @return Json
	 */
    function comment_list(int $goods_id, mixed $comment_id, Request $request): Json
    {
        $top_id = 0;
        if (!empty($comment_id)) {
            $row = SecGoodsComment::find($comment_id);
            if ($row->pid == 0) {
                //顶级评论 放在第一条
                $top_id = $row->id;
            } else {
                //子评论 找出顶级评论
                $row = SecGoodsComment::find($row->pid);
                $top_id = $row->id;
            }
        }
        $SecGoodsCommentModel = new SecGoodsComment();
        $res = $SecGoodsCommentModel
            ->where(['goods_id' => $goods_id, 'pid' => 0])
            ->withCount('comment')
            ->with([
                'users',
                'comment' => function (Query $query) use ($request, $comment_id) {
                    $query
                        ->with(['users', 'to_users', 'users_like' => function (Query $query) use ($request) {
                            $query->where(['users_id' => $request->users_id, 'type' => 'secgoods_comment']);
                        }])
                        ->when(!empty($comment_id), function (Query $query) use ($comment_id) {
                            $query->field("*,IF(id = $comment_id,1,0) AS top")->order(['top' => 'desc', 'id' => 'desc']);
                        }, function (Query $query) {
                            $query->order(['id' => 'desc']);
                        })
                        ->limit($this->comment_list_rows);
                },
                'users_like' => function (Query $query) use ($request) {
                    $query->where(['users_id' => $request->users_id, 'type' => 'secgoods_comment']);
                }])
            ->when(!empty($comment_id), function (Query $query) use ($top_id) {
                $query->field("IF(id = $top_id,1,0) AS top")->order(['top' => 'desc', 'id' => 'desc']);
            }, function (Query $query) {
                $query->order(['id' => 'desc']);
            })
            ->paginate()
            ->items();
        writeJson($res);
    }

    /**
     * 评论详情
     * @param int $id
     * @param mixed $comment_id
     * @param Request $request
     * @return Json
     */
    function comment_detail(int $id, mixed $comment_id, Request $request)
    {
        $child = false;
        if (!empty($comment_id)) {
            $row = SecGoodsComment::find($comment_id);
            if ($row->pid != 0) {
                //二级评论
                $child = true;
            }
        }
        $res = SecGoodsComment::where(['pid' => $id])
            ->with(['users', 'to_users', 'users_like' => function (Query $query) use ($request) {
                $query->where(['users_id' => $request->users_id, 'type' => 'secgoods_comment']);
            }])
            ->when($child, function (Query $query) use ($comment_id) {
                $query->where('id', '<>', $comment_id);
            })
            ->order('id', 'desc')
            ->paginate($this->comment_detail_rows)
            ->items();
        writeJson($res);
    }


    /**
     * 评论点赞
     * @param Request $request
     * @return Json
     */
    function comment_like(Request $request)
    {
        $id = $request->param('id');
        $res = UsersService::like($id, $request->users_id, 'secgoods_comment');
        $res ? event('SecGoodsCommentIncLike', $id) : event('SecGoodsCommentDecLike', $id); //增加/减少  点赞数量
        if ($res) {
            $pro = SecGoodsComment::find($id);
            UsersRelated::create(['users_id' => $pro->users_id, 'type' => 4, 'from_users_id' => $request->users_id, 'scene' => 'SecGoods', 'pro_id' => $id]);
        }
        writeJson($res);
    }

    /**
     * 二手物品-点赞
     * @param Request $request
     * @return Json
     */
    function like(Request $request)
    {
        $id = $request->post('id');
        $res = UsersService::like($id, $request->users_id, 'secgoods');
        $res ? event('SecGoodsIncLike', $id) : event('SecGoodsDecLike', $id); //增加/减少  点赞数量
        if ($res) {
            $pro = SecGoods::find($id);
            UsersRelated::create(['users_id' => $pro->users_id, 'type' => 3, 'from_users_id' => $request->users_id, 'scene' => 'SecGoods', 'pro_id' => $id]);
        }
        writeJson($res);
    }
	
	/**
	 * 二手物品-收藏
	 * @param Request $request
	 * @return Json
	 */
    function collect(Request $request)
    {
        $id = $request->post('id/d');
        if (empty($id)) {
	        writeJson(0,'收藏失败');
        }
        $res = UsersService::collect($id, $request->users_id, 'secgoods');
        $res ? event('SecGoodsIncCollect', $id) : event('SecGoodsDecCollect', $id); //增加/减少  收藏数量
        if ($res) {
            $pro = SecGoods::find($id);
            UsersRelated::create(['users_id' => $pro->users_id, 'type' => 7, 'from_users_id' => $request->users_id, 'scene' => 'SecGoods', 'pro_id' => $id]);
        }
        writeJson($res);
    }
	
	/**
	 * 二手物品-想要
	 * @param Request $request
	 * @return Json
	 */
    function want(Request $request)
    {
        $id = $request->post('id');
        $res = UsersService::want($id, $request->users_id, 'secgoods');
        $res ? event('SecGoodsIncWant', $id) : 0; //增加/减少  收藏数量
        writeJson();
    }



	
	function map_detail(Request $request): Json
	{
		$params = $request->param(); // latitude  longitude distance
		$lat = $params['latitude'];
		$lng = $params['longitude'];
		$res = SecGoods::field("*,(6371 * acos (cos ( radians($lat) ) * cos( radians( latitude ) ) * cos( radians(longitude) - radians( $lng ) ) + sin ( radians( $lat ) ) * sin( radians( latitude ) ))) AS distance")
			->where(['latitude'=>$lat,'longitude'=>$lng])
			->with(['users'])
			->filter(function ($data) use($lat,$lng) {
				if (empty($lat) || empty($lng)) {
					$data->distance_text = '';
				} else {
					if ($data->distance == 0) {
						$data->distance_text = '0m';
					} elseif (0 < $data->distance && $data->distance < 1) {
						$data->distance_text = bcmul((string)$data->distance, '1000') . 'm';
					} else {
						$data->distance_text = bcmul((string)$data->distance, '1', 1) . 'km';
					}
				}
				
			})
			->select();
		writeJson($res);
	}
	
	/**
	 * 删除
	 * @param Request $request
	 * @return Json
	 */
    function delete(Request $request)
    {
        $id = $request->post('id/d');
        SecGoods::where(['users_id' => $request->users_id, 'id' => $id])->findOrFail()->delete();
        writeJson();
    }
	
	/**
	 * 上架/下架
	 * @param Request $request
	 * @return Json
	 */
    function up_down(Request $request)
    {
        $id = $request->post('id/d');
        $status = $request->post('status/d');
        $row = SecGoods::where(['users_id' => $request->users_id, 'id' => $id])->findOrFail();
        $row->save(['status' => $status]);
        writeJson();
    }
	
	/**
	 * 编辑
	 * @param Request $request
	 * @return Json
	 */
    function edit(Request $request)
    {
        $params = $request->param();
        $row = SecGoods::findOrFail($params['id']);
        if ($request->isGet()) {
            writeJson($row);
        }
        $row->save($params);
        writeJson();
    }


}